var mqtt = require('../../utils/mqtt.min.js') //根据自己存放的路径修改 加载mqtt.min.js这个模块
const crypto = require('../../utils/hex_hmac_sha1.js'); //根据自己存放的路径修改 加载hmac_sha1.js这个模块
var util = require('../../utils/time.js');//加载自己设计的time.js模块

//var keep_connect;

var idx_flag = false;

var idx_flag1 = false;

var idx_flag2 = false;
//var connect_flag_test;

Page({
  data: { //是页面第一次渲染使用的初始数据
    Temp:"--",
    Humidity:"--",
    CH2O:"--",
    pm25:"--",
    status:"未开启",

  },

  //生命周期函数--监听页面加载 页面加载时触发，一个页面只会调用一次，可以在onLoad的参数中获取当前页面路径中的参数
onLoad: function (options) 
{
  if(getApp().globalData.connect_flag == false)
  {
    this.ConnectToAliyun(1);
  }
  console.log("iottest onLoad:",getApp().globalData.connect_flag);
},

  //生命周期函数--监听页面显示 页面显示/切入前台时触发
onShow:function()
{
  //this.loaddata();
  //注意：这里在程序运行后会直接进行连接，如果你要真机调试，记得关掉模拟器或者使用一个按钮来控制连接，以避免模拟器和真机同时进行连接导致两边都频繁断线重连！
  console.log("iottest onShow:",getApp().globalData.connect_flag);
  this.get_time();
  this.KeepConnect();

  //var time = util.formatTime(new Date());

  // this.setData({
  //   time:time
  // });
},

//页面隐藏/切入后台时触发
onHide:function()
{
  //console.log("gaga");
  // try{
  //   wx.setStorageSync('connect_flag', 0);
  // }catch(e){}
  // finally{
  //   //console.log("store connect_flag success");
  // }
  //keep_connect.end();//切换到别的页面时，则断开与物联网平台的连接
  console.log("断开连接成功!");
  //getApp().globalData.connect_flag = false;
},

ConnectToAliyun(flag)
{
  getApp().globalData.connect_flag = true;
  
  const deviceConfig = 
  {
    productKey: "a1ay7f9DL7I",
    deviceName: "Applet_test",
    deviceSecret: "dd77391750a0684818fccb881c3bf28a",
    regionId: "cn-shanghai"//根据自己的区域替换
  };//只读变量

  const options = this.initMqttOptions(deviceConfig);
  console.log(options)
    
  //替换productKey为你自己的产品的（注意这里是wxs，不是wss，否则你可能会碰到ws不是构造函数的错误）
   //注意：订阅主题，替换productKey和deviceName(这里的主题可能会不一样，具体请查看控制台-产品详情-Topic 类列表下的可订阅主题)
  //const client = mqtt.connect('wxs://a1ay7f9DL7I.iot-as-mqtt.cn-shanghai.aliyuncs.com',options);

  getApp().globalData.keep_connect = mqtt.connect('wxs://a1ay7f9DL7I.iot-as-mqtt.cn-shanghai.aliyuncs.com',options);
  
  getApp().globalData.keep_connect.on('connect', function () 
  {
    if(flag == 1)
    {
      wx.showToast({
        title: '连接服务器成功',
        icon:'none'
      });
    }

    getApp().globalData.keep_connect.subscribe('/a1ay7f9DL7I/Applet_test/user/get', function (err) 
    {
      if (!err) 
      {
        if(flag == 1)
        {
          setTimeout(function(){
            wx.showToast({
              title: '订阅成功',
              icon:'none'
            });
          }, 100);
        }
      
        // try{
        //     wx.setStorageSync('connect_flag', 1);
        //   }catch(e){}
        // finally{
        //     //console.log("store connect_flag success");
        // }
      }
    })
  });

  //keep_connect = client;
},

KeepConnect()
{
    var that = this;//声明一个变量，that = this

    // var value = wx.getStorageSync('connect_flag');
    // //console.log(value);
    // if(value == 0)
    // {
    //   this.ConnectToAliyun(0);
    // }
    console.log("keepConnect,", getApp().globalData.connect_flag);
    // if(getApp().globalData.connect_flag == false)
    // {
    //   this.ConnectToAliyun(0);
    // }
   

	//接收消息监听
  getApp().globalData.keep_connect.on('message', function (topic, message){
      // message is Buffer
      var msg = message.toString();//该变量只在该命令的代码块有效
      
      console.log(msg);
      
      if(msg != "" || msg.indexOf("status") != -1)
      {
        that.setData({
          status: "已开启"
        });
      }

      if(msg.indexOf("temp") != -1 && msg.indexOf("humi") != -1)
      {
        var temp = msg[8] + msg[9] + msg[10] + msg[11];
        var humi = msg[20] + msg[21] + msg[22] + msg[23];
        
        if(idx_flag == true)
        {
          //console.log(111);
          for(var i = 0; i < 9; i++)
          {
            getApp().globalData.ten_tempeature[i] = getApp().globalData.ten_tempeature[i + 1];

            getApp().globalData.ten_humi[i] = getApp().globalData.ten_humi[i + 1]; 

            getApp().globalData.ten_time[i] = getApp().globalData.ten_time[i + 1];
          } 

          //console.log(222);

          getApp().globalData.ten_tempeature[9] = temp;

          getApp().globalData.ten_humi[9] = humi;

          getApp().globalData.ten_time[9] = util.hourtime(new Date());
        }
        else
        {
          getApp().globalData.ten_tempeature[getApp().globalData.idx] = temp;

          getApp().globalData.ten_humi[getApp().globalData.idx] = humi;
  
          getApp().globalData.ten_time[getApp().globalData.idx] = util.hourtime(new Date());
  
          console.log(getApp().globalData.ten_tempeature[getApp().globalData.idx]);
  
          console.log(getApp().globalData.ten_humi[getApp().globalData.idx]);
  
          console.log(getApp().globalData.ten_time[getApp().globalData.idx]);
  
          getApp().globalData.idx++;

          console.log(getApp().globalData.idx);
        }
    
        if(getApp().globalData.idx >= 10 && idx_flag == false)
        {
          idx_flag = true;
          getApp().globalData.enough_ten_flag = true;
          getApp().globalData.idx = 9;
          //getApp().globalData.idx =;
        }
        // else if(getApp().globalData.idx < 0)
        // {
        //   idx_flag = false;
        //   getApp().globalData.idx = 0;
        // }

       

       
        // getApp().globalData.ten_time[get]
        //console.log(humi);
        //that.setData({Humidity: humi});
     
        //console.log(temp);
        //console.log(humi);
        //let that = this;
        that.setData({Temp: temp, Humidity: humi});
      }

      if(msg.indexOf("pm25") != -1)
      {
        console.log(msg);
        if(msg.length == 13)
        {
          var pm25 = msg[8] + msg[9] + msg[10] + msg[11];
        }
        else if(msg.length == 14)
        {
          var pm25 = msg[8] + msg[9] + msg[10] + msg[11] + msg[12];
        }
        else if(msg.length == 12)
        {
          var pm25 = msg[8] + msg[9] + msg[10];
        }

        if(idx_flag1 == true)
        {
          for(var i = 0; i < 9; i++)
          {
            getApp().globalData.ten_air[i] = getApp().globalData.ten_air[i + 1];

            getApp().globalData.ten_time1[i] = getApp().globalData.ten_time1[i + 1];
          } 

          getApp().globalData.ten_air[9] = pm25;

          getApp().globalData.ten_time1[9] = util.hourtime(new Date());
        }
        else
        {
          getApp().globalData.ten_air[getApp().globalData.idx1] = pm25;

          getApp().globalData.ten_time1[getApp().globalData.idx1] = util.hourtime(new Date());

          getApp().globalData.idx1++;
          console.log(getApp().globalData.idx1);
        }

        if(getApp().globalData.idx1 >= 10 && idx_flag1 == false)
        {
          idx_flag1 = true;
          getApp().globalData.enough_ten_flag1 = true;
          getApp().globalData.idx1 = 9;
          //getApp().globalData.idx =;
        }

        that.setData({pm25: pm25});
      }

      if(msg.indexOf("ppb") != -1)
      {
        if(msg.length == 12)
        {
          var ppb = msg[7] + msg[8] + msg[9] + msg[10];
        }
        else if(msg.length == 11)
        {
          var ppb = msg[7] + msg[8] + msg[9];
        }
        else if(msg.length == 10)
        {
          var ppb = msg[7] + msg[8];
        }
        else if(msg.length == 9)
        {
          var ppb = msg[7];
        }
      
        if(idx_flag2 == true)
        {
          for(var i = 0; i < 9; i++)
          {
            getApp().globalData.ten_ppb[i] = getApp().globalData.ten_ppb[i + 1];

            getApp().globalData.ten_time2[i] = getApp().globalData.ten_time2[i + 1];
          } 

          getApp().globalData.ten_ppb[9] = ppb;

          getApp().globalData.ten_time2[9] = util.hourtime(new Date());
        }
        else
        {
          getApp().globalData.ten_ppb[getApp().globalData.idx2] = ppb;
  
          getApp().globalData.ten_time2[getApp().globalData.idx2] = util.hourtime(new Date());
  
          console.log(getApp().globalData.ten_ppb[getApp().globalData.idx2]);
  
          console.log(getApp().globalData.ten_time2[getApp().globalData.idx2]);
  
          getApp().globalData.idx2++;

          console.log(getApp().globalData.idx2);
        }

        if(getApp().globalData.idx2 >= 10 && idx_flag2 == false)
        {
          idx_flag2 = true;
          getApp().globalData.enough_ten_flag2 = true;
          getApp().globalData.idx2 = 9;
          //getApp().globalData.idx =;
        }

        console.log(ppb);

        that.setData({CH2O: ppb});
      }
     //关闭连接 
      //keep_connect.end();
    })

    //如果连接错误
    getApp().globalData.keep_connect.on('error', function(error)
    {
      console.log('错误信息:' + error);
      client.end();

      //延时1000ms
      setTimeout(function(){
      }, 1000);

      //再次连接
      const client = mqtt.connect('wxs://a1ay7f9DL7I.iot-as-mqtt.cn-shanghai.aliyuncs.com',options);
     
      //如果连接成功
      client.on('connect', function(){
        console.log('再次连接服务器成功');
        //注意：订阅主题，替换productKey和deviceName(这里的主题可能会不一样，具体请查看控制台-产品详情-Topic 类列表下的可订阅主题)
        client.subscribe('/a1ay7f9DL7I/Applet_test/user/get', function(err) 
        {
          if (!err) 
          {
              console.log('订阅成功！');
          }
        })
      })
    })
  },

  //IoT平台mqtt连接参数初始化
 initMqttOptions(deviceConfig) {

    const params = {
      productKey: deviceConfig.productKey,
      deviceName: deviceConfig.deviceName,
      timestamp: Date.now(),
      clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT参数
    const options = {
      keepalive: 60, //60s
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成clientId，username，password
    options.password = this.signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;

    return options;
  },

/*
  生成基于HmacSha1的password
  参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
*/
 signHmacSha1(params, deviceSecret) {

    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
      list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.hex_hmac_sha1(deviceSecret, contentStr);
  },

get_time()
{
  var that = this;
  setInterval(function()
  {
    that.setData({
      time: util.formatTime(new Date())
    });
  }, 1000);
}

})


